<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
        title="收货地址"
        @click-left="$router.go(-1)"
        left-arrow
      ></van-nav-bar>
    </header>
    <div class="content">
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="selectAddress"
      />
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { AddressList, Toast, NavBar } from 'vant'
import { getAddressData, updateOrderAddress } from '@/api'
Vue.use(AddressList)
Vue.use(Toast)
Vue.use(NavBar)
export default {
  data () {
    return {
      chosenAddressId: '',
      list: []
    }
  },
  mounted () {
    getAddressData({
      userid: localStorage.getItem('userid')
    }).then(res => {
      console.log(res.data.data)
      const arr = []
      res.data.data.map((item, index) => {
        let str = ''
        // 如果遇到直辖市，省份和城市保留一个
        if (item.province === item.city) {
          str += item.province
        } else {
          str += item.province + item.city
        }
        str += item.county
        str += item.addressDetail
        if (item.isDefault) {
          this.chosenAddressId = index + 1
        }
        arr.push({
          id: index + 1,
          // 这里和老师不一样，如果直接设置id值为addressid的值，默认选中状态就会失效
          addressid: item.addressid,
          name: item.name,
          tel: item.tel.replace(item.tel.slice(3, 7), '****'),
          address: str,
          isDefault: item.isDefault === 1
        })
      })
      this.list = arr
    })
  },
  methods: {
    onAdd () {
      Toast('新增地址')
      this.$router.push('/addressadd')
    },
    onEdit (item, index) {
      // Toast('编辑地址:' + index)
      this.$router.push({ path: '/addedit/' + item.addressid })
    },
    selectAddress (item, index) {
      const { orderid } = this.$route.query
      console.log(index, item)
      console.log(orderid)
      updateOrderAddress({
        addressid: item.addressid,
        orderid
      }).then(res => {
        if (res.data.code === '200') {
          this.$router.go(-1)
        }
      })
    }
  }
}
</script>
